package com.gzgs.dao;

import com.gzgs.domain.Permission;
import com.gzgs.domain.Role;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface RoleDao {
    //根据用户id查询出所有对应的角色
    @Select("select * from role where id in (select roleId from users_role where userId=#{userId})")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "roleName", column = "roleName"),
            @Result(property = "roleDesc", column = "roleDesc"),
            @Result(property = "permissions",column = "id",javaType = java.util.List.class,many = @Many(select = "com.gzgs.dao.PermissionDao.findPermissionByRoleId"))
    })
    public List<Role> findRoleByUserId(String userId) throws Exception;


    /**
     * 查询所有角色
     * @return
     */
    @Select("select * from role")
    public List<Role> findAll()throws Exception;

    /**
     * 添加角色
     * @param role
     * @throws Exception
     *  String id;
     *     private String roleName;
     *     private String roleDesc;
     */
    @Insert("insert into role(roleName,roleDesc) values(#{roleName},#{roleDesc})")
    void saveRole(Role role) throws Exception;

    /**
     * 通过指定id查询角色
     * @param id
     * @return
     * @throws Exception
     */
    @Select("select * from role where id=#{id}")
    @Results({
            @Result(id = true,column = "id",property = "id"),
            @Result(column = "roleName",property = "roleName"),
            @Result(column = "roleDesc",property = "roleDesc"),
            @Result(column = "id",property = "permissions",javaType = java.util.List.class,many = @Many(select = "com.gzgs.dao.PermissionDao.findPermissionByRoleId")),
    })
    Role findById(String id)throws Exception;

    /**
     * 删除角色
     * @param id
     * @throws Exception
     */
    @Delete("delete from role where id=#{id}")
    void deleteRole(String id)throws Exception;

    @Delete("delete from role_permission where roleId=#{id}")
    void deleteFromRole_Permission(String id)throws Exception;

    @Delete("delete from users_role where roleId=#{id}")
    void deleteFromUser_Role(String id) throws Exception;

    @Select("select * from permission where id not in (select permissionId from role_permission where roleId=#{roleId})")
    List<Permission> findOtherPermissions(String roleId)throws Exception;

   
    @Insert("insert into role_permission(roleId,permissionId) values(#{roleId},#{permissionId})")
    void addPermissionToRole(@Param("roleId") String roleId, @Param("permissionId") String permissionId)throws Exception;
}
